import { GameEventData, GameEventType, BrickPartyBlock, BlockAnimationState, GameFrameData, GamePhase } from "../bean/GameBean";
import { WebSocketManager } from "../net/WebSocketManager";
import { MessageId } from "../net/MessageId";
import { ReceivedMessageBean } from "../net/MessageBaseBean";
import { EventType } from "../common/EventCenter";
import { GameMgr } from "../common/GameMgr";
import GamePageController from "./GamePageController";

/**
 * 游戏事件处理器
 * 负责处理来自服务器的游戏事件消息，并转发给相应的处理器
 * 支持统一数字事件系统，处理方块动画相关事件
 */
export class GameEventHandler {
    private gamePageController: GamePageController | null = null;
    
    constructor() {
        // 构造函数中不进行初始化，等待外部调用
    }
    
    /**
     * 设置游戏页面控制器
     */
    public setGamePageController(controller: GamePageController): void {
        this.gamePageController = controller;
        
    }
    
    /**
     * 注册WebSocket消息处理器
     */
    public registerWebSocketHandlers(): void {
        // 使用事件系统监听WebSocket消息
        GameMgr.Event.AddEventListener(EventType.ReceiveMessage, this.onReceiveMessage, this);
      
    }
    
    /**
     * 处理接收到的WebSocket消息
     */
    private onReceiveMessage(messageBean: ReceivedMessageBean): void {
        // 处理GameFrame消息，其中包含游戏事件
        if (messageBean.msgId === "GameFrame") {
            const frameData = messageBean.data as GameFrameData;
            this.handleGameFrame(frameData);
        }
        // 可以根据需要添加其他消息类型的处理
    }
    
    /**
     * 处理GameFrame消息，提取其中的游戏事件
     */
    private handleGameFrame(frameData: GameFrameData): void {
      
        
        // 处理每个游戏事件
        for (const gameEvent of frameData.gameEvents) {
            this.handleGameEvent(gameEvent);
        }
    }
    
    /**
     * 处理游戏事件，转换为标准格式
     */
    private handleGameEvent(gameEvent: GameEventData): void {
     
        
        // 根据事件类型处理不同的数据结构
        if (gameEvent.eventType >= 1 && gameEvent.eventType <= 6) {
            // 游戏阶段事件
            this.handlePhaseEvent(gameEvent.eventType, gameEvent);
        } else if (gameEvent.eventType === 7 || gameEvent.eventType === 9) {
            // 玩家死亡/离开事件
            this.handlePlayerEvent(gameEvent.eventType, gameEvent);
        }
    }
    
    /**
     * 处理游戏阶段事件
     */
    private handlePhaseEvent(eventType: number, eventData: GameEventData): void {
      
        
        // 直接转发事件数据，因为已经是标准格式
        this.forwardToGameController(eventData);
    }
    
    /**
     * 处理玩家事件
     */
    private handlePlayerEvent(eventType: number, eventData: GameEventData): void {
       
        
        // 直接转发事件数据，因为已经是标准格式
        this.forwardToGameController(eventData);
    }
    
    
    /**
     * 转发事件到游戏控制器
     */
    private forwardToGameController(gameEventData: GameEventData): void {
        if (!this.gamePageController) {
            console.error("GamePageController未设置，无法处理游戏事件");
            return;
        }
        
       
        this.gamePageController.handleGameEvent(gameEventData);
    }
    
    
    /**
     * 验证事件数据
     */
    private validateEventData(eventData: GameEventData): boolean {
        if (!eventData) {
            console.error("事件数据为空");
            return false;
        }
        
        if (typeof eventData.eventType !== 'number' || eventData.eventType < 1 || eventData.eventType > 10) {
            console.error(`无效的事件类型: ${eventData.eventType}`);
            return false;
        }
        
        // 验证需要方块数据的事件类型
        if ([GameEventType.SHAKING, GameEventType.FALLING, GameEventType.RESTORING].includes(eventData.eventType)) {
            if (!eventData.blocks || !Array.isArray(eventData.blocks)) {
                console.error(`事件类型${eventData.eventType}需要方块数据`);
                return false;
            }
            
            // 验证方块数据
            for (const block of eventData.blocks) {
                if (!this.validateBlockData(block)) {
                    return false;
                }
            }
        }
        
        // 验证随机种子
        if ([GameEventType.SHAKING, GameEventType.FALLING, GameEventType.RESTORING].includes(eventData.eventType)) {
            if (typeof eventData.randomSeed !== 'number') {
                console.error(`事件类型${eventData.eventType}需要随机种子`);
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 验证方块数据
     */
    private validateBlockData(block: BrickPartyBlock): boolean {
        if (!block) {
            console.error("方块数据为空");
            return false;
        }
        
        if (typeof block.x !== 'number' || block.x < 0 || block.x > 8) {
            console.error(`无效的方块X坐标: ${block.x}`);
            return false;
        }
        
        if (typeof block.y !== 'number' || block.y < 0 || block.y > 8) {
            console.error(`无效的方块Y坐标: ${block.y}`);
            return false;
        }
        
        return true;
    }
    
    /**
     * 创建测试事件数据（用于调试）
     */
    public createTestEvent(eventType: GameEventType, blockCount: number = 10): GameEventData {
        const testBlocks: BrickPartyBlock[] = [];
        
        // 生成随机测试方块
        for (let i = 0; i < blockCount; i++) {
            testBlocks.push({
                id: i + 1,
                x: Math.floor(Math.random() * 9),
                y: Math.floor(Math.random() * 9),
                blockType: 1,
                animationState: BlockAnimationState.NONE,
                animationDelay: 0
            });
        }
        
        const testEvent: GameEventData = {
            eventType: eventType,
            currentRound: 1,
            countDown: 2000,
            randomSeed: Math.floor(Math.random() * 1000000),
            message: this.getEventMessage(eventType),
            blocks: [GameEventType.SHAKING, GameEventType.FALLING, GameEventType.RESTORING].includes(eventType) ? testBlocks : undefined
        };
        
        return testEvent;
    }
    
    /**
     * 获取事件消息
     */
    private getEventMessage(eventType: GameEventType): string {
        switch (eventType) {
            case GameEventType.WAITING:
                return "游戏即将开始";
            case GameEventType.ROUND_WAITING:
                return "等待下一回合";
            case GameEventType.SHAKING:
                return "方块开始松动";
            case GameEventType.FALLING:
                return "方块开始掉落";
            case GameEventType.RESTORING:
                return "方块开始补齐";
            case GameEventType.ENDING:
                return "游戏结束";
            case GameEventType.PLAYER_DEATH:
                return "玩家死亡";
            case GameEventType.PLAYER_DISCONNECT:
                return "玩家断线";
            case GameEventType.PLAYER_LEAVE:
                return "玩家离开";
            case GameEventType.PLAYER_RECONNECT:
                return "玩家重连";
            default:
                return "未知事件";
        }
    }
    
 
    /**
     * 清理资源
     */
    public cleanup(): void {
        if (this.gamePageController) {
            // 移除WebSocket消息监听
            GameMgr.Event.RemoveEventListener(EventType.ReceiveMessage, this.onReceiveMessage, this);
            
            this.gamePageController = null;
           
        }
    }
}
